package com.example.administrator.hqq.activity.home;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.alertview.AlertViewFactory;
import com.example.administrator.hqq.activity.complain.ChatComplainActivity;
import com.example.administrator.hqq.activity.mine.AmendUserDataActivity;
import com.example.administrator.hqq.base.BaseConversationFragment;
import com.example.administrator.hqq.base.MyApplication;
import com.example.administrator.hqq.base.MyConversationClickListener;
import com.example.administrator.hqq.base.MyFragmentActivity;
import com.example.administrator.hqq.bean.Complain;
import com.example.administrator.hqq.bean.GroupEvent;
import com.example.administrator.hqq.bean.QNTokenBean;
import com.example.administrator.hqq.bean.group.GetGroupSettingsBean;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.utils.HintWordsUtils;
import com.example.administrator.hqq.utils.UploadManagerUtils;
import com.example.administrator.hqq.utils.transform.GlideCircleTransform;
import com.google.gson.Gson;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imkit.actions.IClickActions;
import io.rong.imkit.mention.RongMentionManager;
import io.rong.imkit.model.UIMessage;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;
import io.rong.message.ImageMessage;
import io.rong.message.RichContentMessage;
import io.rong.message.TextMessage;
import io.rong.message.VoiceMessage;
import io.rong.push.RongPushClient;
import okhttp3.Call;
import retrofit2.http.Url;

public class ChatRoomActivity extends MyFragmentActivity {

    @BindView(R.id.return_auto)
    AutoRelativeLayout returnAuto;
    @BindView(R.id.group_title)
    TextView groupTitle;
    @BindView(R.id.setting_group)
    AutoLinearLayout settingGroup;
    @BindView(R.id.delete_friend)
    AutoLinearLayout deleteFriend;
    @BindView(R.id.from_text)
    TextView fromText;
    private String TAG = this.getClass().getSimpleName();
    private String group_member_type;
    //这里group_Id 指的是聊天室id 也就是群id或者私聊的id
    private String group_id;
    private List<UserInfo> UserData;
    private String stringValue;
    private String conversationID;
    private List<String> strings;
    private AlertDialog alertDialog;
    private String from_user_id;
    private String target_user_id;
    private String channel_type ;
    private String message_time ;
    private String message_uid ;
    private String source="Android";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_room);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initview();
        initdata();
        setConversation();
        setRongIMSendMessageListener();
    }

    private void setConversation() {
        RongIM.setConversationClickListener(new MyConversationClickListener());
    }

    private void initview() {
        strings = new ArrayList<>();
        //判断是否是消息多选功能
        if (getIntent().getBooleanExtra(LoongsConfig.is_chat_room_more, false)) {
            //设置消息多选页面
            settingGroup.setVisibility(View.GONE);
            FragmentManager supportFragmentManager = getSupportFragmentManager();
            BaseConversationFragment fragmentById = (BaseConversationFragment) supportFragmentManager.findFragmentById(R.id.conversation);
            fragmentById.setMoreActionState(new UIMessage());
            List<IClickActions> moreClickActions = fragmentById.getMoreClickActions();
            for (int i = 0; i < moreClickActions.size(); i++) {
                moreClickActions.get(i).obtainDrawable(ChatRoomActivity.this);
                moreClickActions.get(i).onClick(fragmentById);
            }
            fragmentById.setOnClickConfirm(new BaseConversationFragment.OnClickConfirm() {
                @Override
                public void onclick(List<Message> messages) {
                    if (messages != null) {
                        Log.e(TAG, "onclick: " + messages.get(0).getUId());
                    }
                    EventBus.getDefault().post(messages);
                    finish();
                }
            });
        } else {
            //根据type值来判断私聊或群聊
            stringValue = SPUtils.getInstance(SPUtils.getInstance().getString(LoongsConfig.user_id)).getString(LoongsConfig.Conversation.ChatConversationType, "");
            conversationID = SPUtils.getInstance(SPUtils.getInstance().getString(LoongsConfig.user_id)).getString(LoongsConfig.Conversation.ConversationID, "");
            if (stringValue.equals(LoongsConfig.Conversation.PRIVATE)) {
                settingGroup.setVisibility(View.GONE);
                //获取私聊用户名称
                deleteFriend.setVisibility(View.VISIBLE);
                getDirectchatTitle();
            } else {
                fromText.setVisibility(View.GONE);
                settingGroup.setVisibility(View.VISIBLE);
                //获取群聊标题
                getGroupTitle();
            }
        }
        UserData = new ArrayList<>();
        //设置@功能
        RongIM.getInstance().setGroupMembersProvider(new RongIM.IGroupMembersProvider() {
            @Override
            public void getGroupMembers(String s, RongIM.IGroupMemberCallback iGroupMemberCallback) {
                getUserInfoList(s, iGroupMemberCallback);
            }
        });
    }

    /**
     * 上传融云消息
     */
    private void upLoadingRongIMMessage(String object_name,String content) {
        OkHttpUtils.get().url(UrlFactory.getRongyunMessage())
                .addParams(LoongsConfig.from_user_id,from_user_id)
                .addParams(LoongsConfig.target_user_id ,target_user_id )
                .addParams(LoongsConfig.channel_type  ,channel_type  )
                .addParams(LoongsConfig.content,content)
                .addParams(LoongsConfig.object_name,object_name)
                .addParams(LoongsConfig.message_time ,message_time)
                .addParams(LoongsConfig.message_uid ,message_uid )
                .addParams(LoongsConfig.source  ,source )
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "upLoadingRongIMMessage++onError: "+e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "upLoadingRongIMMessage++onResponse: "+response);
            }
        });
    }

    /**
     * 监听融入发送的消息
     */
    private void setRongIMSendMessageListener() {
        RongIM.getInstance().setSendMessageListener(new RongIM.OnSendMessageListener() {
            @Override
            public Message onSend(Message message) {
                return message;
            }

            @Override
            public boolean onSent(Message message, RongIM.SentMessageErrorCode sentMessageErrorCode) {
                MessageContent messageContent = message.getContent();
                message_uid=message.getUId();
                channel_type=message.getConversationType().toString();
                message_time=message.getSentTime()+"";
                target_user_id=message.getTargetId();
                from_user_id=message.getSenderUserId();
                if (messageContent instanceof TextMessage) {//文本消息
                    TextMessage textMessage = (TextMessage) messageContent;
                    //上传文本消息
                    upLoadingRongIMMessage("TxtMsg",textMessage.getContent());
                    Log.e(TAG, "文本消息onSent-TextMessage:" + textMessage.getContent());
                } else if (messageContent instanceof ImageMessage) {//图片消息
                    ImageMessage imageMessage = (ImageMessage) messageContent;
                    //上传图片消息
                    upLoadingRongIMMessage("ImgMsg",imageMessage.getRemoteUri().toString());
                    Log.e(TAG, "图片消息onSent-ImageMessage:" + imageMessage.getRemoteUri().toString());
                } else if (messageContent instanceof VoiceMessage) {//语音消息
                    VoiceMessage voiceMessage = (VoiceMessage) messageContent;
                    //上传语音消息
                    final File vcFile = new File(voiceMessage.getUri().getPath());
                    OkHttpUtils.get().url(UrlFactory.getQNToken())
                            .addParams(LoongsConfig.id, message_uid)
                            .addParams(LoongsConfig.type, LoongsConfig.VOICE)
                            .build().execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.e(TAG, "onError: " + e.getMessage());
                        }

                        @Override
                        public void onResponse(String s,int id) {
                            Log.e(TAG, "onResponse: " + s);
                            Gson gson = new Gson();
                            QNTokenBean qnTokenBean = gson.fromJson(s, QNTokenBean.class);
                            if (qnTokenBean.getCode() == 200)
                                UploadManagerUtils.getUploadManager().put(vcFile, qnTokenBean.getKey(), qnTokenBean.getToken(), new UpCompletionHandler() {
                                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                                    @Override
                                    public void complete(String key, ResponseInfo info, JSONObject res) {
                                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                                        if (info.isOK()) {
                                            //上传图片消息
                                            upLoadingRongIMMessage("VcMsg","");
                                        } else {
                                            //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                                        }
                                        Log.i(TAG, key + ", " + info + ", " + res);
                                    }
                                }, null);
                        }
                    });
                    Log.e(TAG, "onSent-voiceMessage:" + voiceMessage.getUri().toString());
                } else if (messageContent instanceof RichContentMessage) {//图文消息
                    RichContentMessage richContentMessage = (RichContentMessage) messageContent;
                    Log.e(TAG, "onSent-RichContentMessage:" + richContentMessage.getContent());
                } else {
                    Log.e(TAG, "onSent-其他消息，自己来判断处理");
                }
                return false;
            }
        });
    }

    /**
     * 设置@功能的数据
     *
     * @param groupID
     * @param iGroupMemberCallback
     */
    private void getUserInfoList(String groupID, final RongIM.IGroupMemberCallback iGroupMemberCallback) {
        OkHttpUtils.get().url(UrlFactory.getGroupSettings())
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.group_id, groupID)
                .addParams(LoongsConfig.type, "1")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "onResponse: " + response);
                Gson gson = new Gson();
                GetGroupSettingsBean getGroupSettingsBean = gson.fromJson(response, GetGroupSettingsBean.class);
                if (getGroupSettingsBean.getCode() == 200) {
                    UserData.clear();
                    for (int i = 0; i < getGroupSettingsBean.getData().getMember().size(); i++) {
                        GetGroupSettingsBean.DataBean.MemberBean memberBean = getGroupSettingsBean.getData().getMember().get(i);
                        UserData.add(new UserInfo(memberBean.getId(), memberBean.getName(), Uri.parse(memberBean.getName())));
                    }
                    iGroupMemberCallback.onGetGroupMembersResult(UserData);
                }
            }
        });
    }

    private void initdata() {
        group_id = SPUtils.getInstance(SPUtils.getInstance().getString(LoongsConfig.user_id)).getString(LoongsConfig.Conversation.ConversationID, "");
        if (!TextUtils.isEmpty(group_id) && !TextUtils.isEmpty(stringValue) && stringValue.equals(LoongsConfig.Conversation.GROUP)) {
            if (!getIntent().getBooleanExtra(LoongsConfig.is_chat_room_more, false)) {
                //判断是群主还是群成员进入该群
            }
        }
    }

    /**
     * 进群检测
     *
     * @param group_id
     */
    private void joinGroupCheck(final String group_id) {
        OkHttpUtils.get().url(UrlFactory.getGroupCheck()).tag(this)
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.group_id, group_id)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "进群检测onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "进群检测onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.getInt("code");
                    String description = jsonObject.getString("description");
                    switch (code) {
                        case 200:
                            group_member_type = "0";
                            break;
                        case 201:
                            group_member_type = "1";
                            break;
                        case 202:
                            group_member_type = "2";
                        case 300008:
                            group_member_type = "2";
                    }
                    if (!TextUtils.isEmpty(group_member_type)) {
                        if ("2".equals(group_member_type)) {
                            ToastUtils.showShort("您已不在该群组");
                        } else {
                            Intent intent = new Intent(ChatRoomActivity.this, ChatRoomSettingActivity.class);
                            intent.putExtra(LoongsConfig.group_member_type, group_member_type);
                            intent.putExtra(LoongsConfig.group_id, group_id);
                            startActivityForResult(intent, 20);
                        }
                    } else {
                        ToastUtils.showShort("此功能暂时维护");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 20 && resultCode == 110) {
            group_member_type = "0";
        }
    }

    @OnClick({R.id.return_auto, R.id.setting_group, R.id.delete_friend})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.return_auto:
                finish();
                break;
            case R.id.setting_group:
                joinGroupCheck(group_id);
                break;
            case R.id.delete_friend:
                strings.clear();
                String[] stringArray = getResources().getStringArray(R.array.delete_friend);
                for (String s : stringArray) {
                    strings.add(s);
                }
                alertDialog = AlertViewFactory.getInstance().showDeleteFriendReport(ChatRoomActivity.this, "评价该用户", "其他严重违法情形,请前往投诉", strings, new AlertViewFactory.DeleteFriendReportOnclicke() {
                    @Override
                    public void submit(int position) {
                        reportFriend(position);
                        alertDialog.cancel();
                    }

                    @Override
                    public void goComplain(int position) {
                        alertDialog.cancel();
                        ChatComplainActivity.start(ChatRoomActivity.this
                                , RongPushClient.ConversationType.PRIVATE.toString()
                                , group_id
                                , group_id
                                , LoongsConfig.ComplainType.PRIVATE.toString());
                    }
                });
                break;
        }
    }

    /**
     * 举报并拉黑好友
     *
     * @param position
     */
    private void reportFriend(int position) {
        OkHttpUtils.get().url(UrlFactory.ReportForum())
                .addParams(LoongsConfig.id, group_id)
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.reason_id, position + 601 + "")
                .addParams(LoongsConfig.type, "5")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e);
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "onResponse: " + response);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response);
                    HintWordsUtils.showMarkeWords(jsonObject.getInt(LoongsConfig.code), jsonObject.getString(LoongsConfig.description));
                    if (jsonObject.getInt(LoongsConfig.code) == 200) {
                        MyApplication.removeRongyunConversation(Conversation.ConversationType.PRIVATE, group_id);
                        Complain complain = new Complain(Complain.Type.DELETE_FRIEND, group_id);
                        EventBus.getDefault().post(complain);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 单聊删除接口
     */
    private void deleteContact(String user_other_id) {
        OkHttpUtils.get().url(UrlFactory.deleteContact())
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.user_other_id, user_other_id)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "删除单聊接口onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "删除单聊接口onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt(LoongsConfig.code) == 200) {

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void getGroupTitle() {
        OkHttpUtils.get().url(UrlFactory.getGroupTitle())
                .addParams(LoongsConfig.group_id, conversationID)
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "群聊标题onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "群聊标题onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt(LoongsConfig.code) == 200) {
                        String title = jsonObject.getString("title");
                        int member_amount = jsonObject.getInt("member_amount");
                        groupTitle.setText(title+"("+member_amount+")");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RongMentionManager.getInstance().setGroupMembersProvider(null);
        EventBus.getDefault().unregister(this);
        RongIM.getInstance().setSendMessageListener(null);
    }

    public void getDirectchatTitle() {
        OkHttpUtils.get().url(UrlFactory.getDirectchatTitle())
                .addParams(LoongsConfig.other_user_id, conversationID)
                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "获取私聊标题onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "获取私聊标题onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt(LoongsConfig.code) == 200) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        groupTitle.setText(data.getString("title"));
                        fromText.setText(data.getString("remark"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(GroupEvent groupEvent) {
        switch (groupEvent.getType()) {
            case DELETE_GROUP:
                finish();
                break;
            case ALTER_GROUP:
                getGroupTitle();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(Complain complain) {
        switch (complain.getType()) {
            case KICK_MEMBER:
                getGroupTitle();
                break;
            case QUIT_GROUP:
                finish();
                break;
            case DELETE_FRIEND:
                finish();
                break;
        }
    }
}
